
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Managing files &#8212; Django 1.11.22.dev20190603194737 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Testing in Django" href="testing/index.html" />
    <link rel="prev" title="Migrations" href="migrations.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.11.22.dev20190603194737 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="migrations.html" title="Migrations">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="testing/index.html" title="Testing in Django">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-files">
            
  <div class="section" id="s-managing-files">
<span id="managing-files"></span><h1>Managing files<a class="headerlink" href="#managing-files" title="Permalink to this headline">¶</a></h1>
<p>This document describes Django’s file access APIs for files such as those
uploaded by a user. The lower level APIs are general enough that you could use
them for other purposes. If you want to handle “static files” (JS, CSS, etc.),
see <a class="reference internal" href="../howto/static-files/index.html"><span class="doc">Managing static files (e.g. images, JavaScript, CSS)</span></a>.</p>
<p>By default, Django stores files locally, using the <a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> and
<a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_URL</span></code></a> settings. The examples below assume that you’re using these
defaults.</p>
<p>However, Django provides ways to write custom <a class="reference internal" href="#file-storage">file storage systems</a> that
allow you to completely customize where and how Django stores files. The
second half of this document describes how these storage systems work.</p>
<div class="section" id="s-using-files-in-models">
<span id="using-files-in-models"></span><h2>Using files in models<a class="headerlink" href="#using-files-in-models" title="Permalink to this headline">¶</a></h2>
<p>When you use a <a class="reference internal" href="../ref/models/fields.html#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> or
<a class="reference internal" href="../ref/models/fields.html#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a>, Django provides a set of APIs you can use
to deal with that file.</p>
<p>Consider the following model, using an <a class="reference internal" href="../ref/models/fields.html#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a> to
store a photo:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">)</span>
    <span class="n">price</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DecimalField</span><span class="p">(</span><span class="n">max_digits</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">decimal_places</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
    <span class="n">photo</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ImageField</span><span class="p">(</span><span class="n">upload_to</span><span class="o">=</span><span class="s1">&#39;cars&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Any <code class="docutils literal notranslate"><span class="pre">Car</span></code> instance will have a <code class="docutils literal notranslate"><span class="pre">photo</span></code> attribute that you can use to get at
the details of the attached photo:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">car</span> <span class="o">=</span> <span class="n">Car</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;57 Chevy&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span>
<span class="go">&lt;ImageFieldFile: chevy.jpg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">name</span>
<span class="go">&#39;cars/chevy.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span>
<span class="go">&#39;/media/cars/chevy.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">url</span>
<span class="go">&#39;http://media.example.com/cars/chevy.jpg&#39;</span>
</pre></div>
</div>
<p>This object – <code class="docutils literal notranslate"><span class="pre">car.photo</span></code> in the example – is a <code class="docutils literal notranslate"><span class="pre">File</span></code> object, which means
it has all the methods and attributes described below.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The file is saved as part of saving the model in the database, so the actual
file name used on disk cannot be relied on until after the model has been
saved.</p>
</div>
<p>For example, you can change the file name by setting the file’s
<a class="reference internal" href="../ref/files/file.html#django.core.files.File.name" title="django.core.files.File.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></a> to a path relative to the file storage’s
location (<a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> if you are using the default
<a class="reference internal" href="../ref/files/storage.html#django.core.files.storage.FileSystemStorage" title="django.core.files.storage.FileSystemStorage"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileSystemStorage</span></code></a>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="k">import</span> <span class="n">settings</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">initial_path</span> <span class="o">=</span> <span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;cars/chevy_ii.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">new_path</span> <span class="o">=</span> <span class="n">settings</span><span class="o">.</span><span class="n">MEDIA_ROOT</span> <span class="o">+</span> <span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">name</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Move the file on the filesystem</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">rename</span><span class="p">(</span><span class="n">initial_path</span><span class="p">,</span> <span class="n">new_path</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span>
<span class="go">&#39;/media/cars/chevy_ii.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span> <span class="o">==</span> <span class="n">new_path</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="s-the-file-object">
<span id="the-file-object"></span><h2>The <code class="docutils literal notranslate"><span class="pre">File</span></code> object<a class="headerlink" href="#the-file-object" title="Permalink to this headline">¶</a></h2>
<p>Internally, Django uses a <a class="reference internal" href="../ref/files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.core.files.File</span></code></a> instance any time it
needs to represent a file.</p>
<p>Most of the time you’ll simply use a <code class="docutils literal notranslate"><span class="pre">File</span></code> that Django’s given you (i.e. a
file attached to a model as above, or perhaps an uploaded file).</p>
<p>If you need to construct a <code class="docutils literal notranslate"><span class="pre">File</span></code> yourself, the easiest way is to create one
using a Python built-in <code class="docutils literal notranslate"><span class="pre">file</span></code> object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files</span> <span class="k">import</span> <span class="n">File</span>

<span class="go"># Create a Python file object using open()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/path/to/hello.world&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">myfile</span> <span class="o">=</span> <span class="n">File</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>Now you can use any of the documented attributes and methods
of the <a class="reference internal" href="../ref/files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> class.</p>
<p>Be aware that files created in this way are not automatically closed.
The following approach may be used to close files automatically:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files</span> <span class="k">import</span> <span class="n">File</span>

<span class="go"># Create a Python file object using open() and the with statement</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/path/to/hello.world&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">myfile</span> <span class="o">=</span> <span class="n">File</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">myfile</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;Hello World&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">myfile</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Closing files is especially important when accessing file fields in a loop
over a large number of objects. If files are not manually closed after
accessing them, the risk of running out of file descriptors may arise. This
may lead to the following error:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ne">IOError</span><span class="p">:</span> <span class="p">[</span><span class="n">Errno</span> <span class="mi">24</span><span class="p">]</span> <span class="n">Too</span> <span class="n">many</span> <span class="nb">open</span> <span class="n">files</span>
</pre></div>
</div>
</div>
<div class="section" id="s-file-storage">
<span id="file-storage"></span><h2>File storage<a class="headerlink" href="#file-storage" title="Permalink to this headline">¶</a></h2>
<p>Behind the scenes, Django delegates decisions about how and where to store files
to a file storage system. This is the object that actually understands things
like file systems, opening and reading files, etc.</p>
<p>Django’s default file storage is given by the <a class="reference internal" href="../ref/settings.html#std:setting-DEFAULT_FILE_STORAGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEFAULT_FILE_STORAGE</span></code></a>
setting; if you don’t explicitly provide a storage system, this is the one that
will be used.</p>
<p>See below for details of the built-in default file storage system, and see
<a class="reference internal" href="../howto/custom-file-storage.html"><span class="doc">Writing a custom storage system</span></a> for information on writing your own file
storage system.</p>
<div class="section" id="s-storage-objects">
<span id="storage-objects"></span><h3>Storage objects<a class="headerlink" href="#storage-objects" title="Permalink to this headline">¶</a></h3>
<p>Though most of the time you’ll want to use a <code class="docutils literal notranslate"><span class="pre">File</span></code> object (which delegates to
the proper storage for that file), you can use file storage systems directly.
You can create an instance of some custom file storage class, or – often more
useful – you can use the global default storage system:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files.storage</span> <span class="k">import</span> <span class="n">default_storage</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files.base</span> <span class="k">import</span> <span class="n">ContentFile</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">path</span> <span class="o">=</span> <span class="n">default_storage</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="s1">&#39;/path/to/file&#39;</span><span class="p">,</span> <span class="n">ContentFile</span><span class="p">(</span><span class="s1">&#39;new content&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">path</span>
<span class="go">&#39;/path/to/file&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
<span class="go">11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">path</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;new content&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="../ref/files/storage.html"><span class="doc">File storage API</span></a> for the file storage API.</p>
</div>
<div class="section" id="s-the-built-in-filesystem-storage-class">
<span id="s-builtin-fs-storage"></span><span id="the-built-in-filesystem-storage-class"></span><span id="builtin-fs-storage"></span><h3>The built-in filesystem storage class<a class="headerlink" href="#the-built-in-filesystem-storage-class" title="Permalink to this headline">¶</a></h3>
<p>Django ships with a <a class="reference internal" href="../ref/files/storage.html#django.core.files.storage.FileSystemStorage" title="django.core.files.storage.FileSystemStorage"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.core.files.storage.FileSystemStorage</span></code></a> class
which implements basic local filesystem file storage.</p>
<p>For example, the following code will store uploaded files under
<code class="docutils literal notranslate"><span class="pre">/media/photos</span></code> regardless of what your <a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> setting is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.core.files.storage</span> <span class="k">import</span> <span class="n">FileSystemStorage</span>

<span class="n">fs</span> <span class="o">=</span> <span class="n">FileSystemStorage</span><span class="p">(</span><span class="n">location</span><span class="o">=</span><span class="s1">&#39;/media/photos&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">photo</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ImageField</span><span class="p">(</span><span class="n">storage</span><span class="o">=</span><span class="n">fs</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../howto/custom-file-storage.html"><span class="doc">Custom storage systems</span></a> work the same way:
you can pass them in as the <code class="docutils literal notranslate"><span class="pre">storage</span></code> argument to a
<a class="reference internal" href="../ref/models/fields.html#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Managing files</a><ul>
<li><a class="reference internal" href="#using-files-in-models">Using files in models</a></li>
<li><a class="reference internal" href="#the-file-object">The <code class="docutils literal notranslate"><span class="pre">File</span></code> object</a></li>
<li><a class="reference internal" href="#file-storage">File storage</a><ul>
<li><a class="reference internal" href="#storage-objects">Storage objects</a></li>
<li><a class="reference internal" href="#the-built-in-filesystem-storage-class">The built-in filesystem storage class</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="migrations.html"
                        title="previous chapter">Migrations</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="testing/index.html"
                        title="next chapter">Testing in Django</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/topics/files.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Jun 03, 2019</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="migrations.html" title="Migrations">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="testing/index.html" title="Testing in Django">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>